﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="ControlHelper.cs" company="http://buginbox.wordpress.com/">
//   Copyright (c) GNU General Public License version 2 (GPLv2)
// </copyright>
// --------------------------------------------------------------------------------------------------------------------

using System.Windows;
using System.Windows.Media;

namespace Wpf.Core.Control
{
    /// <summary>
    /// Helper pour implémenter les éléments de l'interface ISFWKBaseControl
    /// </summary>
    public class ControlHelper
    {
        #region UniqueId

        /// <summary>
        /// Brose control hierarchy to set unique id
        /// </summary>
        /// <param name="uniqueId">
        /// The unique id. 
        /// </param>
        /// <param name="ctrl">
        /// The ctrl. 
        /// </param>
        public static void UniqueIdParentRecursive(ref string uniqueId, DependencyObject ctrl)
        {
            if (ctrl is IControlBase)
            {
                if (uniqueId == string.Empty)
                {
                    uniqueId = GetControlName(ctrl);
                }
                else
                {
                    uniqueId = GetControlName(ctrl) + "." + uniqueId;
                }
            }

            if (LogicalTreeHelper.GetParent(ctrl) != null)
            {
                if (LogicalTreeHelper.GetParent(ctrl) != null && LogicalTreeHelper.GetParent(ctrl) != null)
                {
                    UniqueIdParentRecursive(ref uniqueId, LogicalTreeHelper.GetParent(ctrl));
                }
            }
            else
            {
                if (VisualTreeHelper.GetParent(ctrl) != null && VisualTreeHelper.GetParent(ctrl) != null)
                {
                    UniqueIdParentRecursive(ref uniqueId, VisualTreeHelper.GetParent(ctrl));
                }
            }
        }

        /// <summary>
        /// Retourne le nom correspondant à ce control Le nom du type est utilisé si la propriété name n'est pas définie
        /// </summary>
        /// <param name="ctrl">
        /// The ctrl. 
        /// </param>
        /// <returns>
        /// The get control name. 
        /// </returns>
        private static string GetControlName(DependencyObject ctrl)
        {
            string name = ctrl.GetValue(FrameworkElement.NameProperty).ToString();

            if (!string.IsNullOrEmpty(name))
            {
                return name;
            }

            return ctrl.GetType().Name;
        }

        #endregion UniqueId
    }
}